"use client";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Plus, Trash2 } from "lucide-react";
import React, { useState } from "react";
import { Button } from "./button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "./dialog";
import { Input } from "./input";

// Data types for different chart types
export type LabelValueData = {
  label: string;
  value: number;
};

export type XYData = {
  x: number;
  y: number;
};

export type ChartDataType = LabelValueData[] | XYData[];

interface ChartDataEditorDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) =&gt; void;
  data: ChartDataType;
  onDataChange: (data: ChartDataType) =&gt; void;
  chartType: "label-value" | "xy";
  title?: string;
}

export function ChartDataEditorDialog({
  open,
  onOpenChange,
  data,
  onDataChange,
  chartType,
  title = "Edit Chart Data",
}: ChartDataEditorDialogProps) {
  const [localData, setLocalData] = useState&lt;ChartDataType&gt;(data);

  React.useEffect(() =&gt; {
    setLocalData(data);
  }, [data]);

  const addRow = () =&gt; {
    if (chartType === "label-value") {
      const newData = [
        ...(localData as LabelValueData[]),
        { label: "", value: 0 },
      ];
      setLocalData(newData as ChartDataType);
    } else {
      const newData = [...(localData as XYData[]), { x: 0, y: 0 }];
      setLocalData(newData as ChartDataType);
    }
  };

  const removeRow = (index: number) =&gt; {
    if (chartType === "label-value") {
      const newData = [...(localData as LabelValueData[])];
      newData.splice(index, 1);
      setLocalData(newData as ChartDataType);
    } else {
      const newData = [...(localData as XYData[])];
      newData.splice(index, 1);
      setLocalData(newData as ChartDataType);
    }
  };

  const updateRow = (index: number, field: string, value: string | number) =&gt; {
    if (chartType === "label-value") {
      const newData = [...(localData as LabelValueData[])];
      newData[index] = {
        ...newData[index],
        [field]: field === "value" ? Number(value) || 0 : value,
      } as LabelValueData;
      setLocalData(newData as ChartDataType);
    } else {
      const newData = [...(localData as XYData[])];
      newData[index] = {
        ...newData[index],
        [field]: field === "x" || field === "y" ? Number(value) || 0 : value,
      } as XYData;
      setLocalData(newData as ChartDataType);
    }
  };

  const validateData = (): boolean =&gt; {
    if (chartType === "label-value") {
      const data = localData as LabelValueData[];
      return data.every(
        (row) =&gt; row.label.trim() !== "" && !Number.isNaN(row.value),
      );
    } else {
      const data = localData as XYData[];
      return data.every((row) =&gt; !Number.isNaN(row.x) && !Number.isNaN(row.y));
    }
  };

  const getRowValidationError = (
    index: number,
    field: string,
  ): string | null =&gt; {
    const row = (localData as (LabelValueData | XYData)[])[index];
    if (!row) return null;

    if (chartType === "label-value") {
      const labelValueRow = row as LabelValueData;
      if (field === "label" && labelValueRow.label.trim() === "") {
        return "Label cannot be empty";
      }
      if (field === "value" && Number.isNaN(labelValueRow.value)) {
        return "Value must be a number";
      }
    } else {
      const xyRow = row as XYData;
      if (
        (field === "x" || field === "y") &&
        Number.isNaN(xyRow[field as keyof XYData] as number)
      ) {
        return "Must be a number";
      }
    }
    return null;
  };

  const handleSave = () =&gt; {
    if (!validateData()) {
      // You could add a toast notification here for validation errors
      return;
    }
    onDataChange(localData);
    onOpenChange(false);
  };

  const handleCancel = () =&gt; {
    setLocalData(data);
    onOpenChange(false);
  };

  return (
    &lt;Dialog open={open} onOpenChange={onOpenChange}&gt;
      &lt;DialogContent
        className="ignore-click-outside/toolbar max-w-2xl max-h-[80vh] overflow-hidden flex flex-col"
        showCloseButton={true}
      &gt;
        &lt;DialogHeader&gt;
          &lt;DialogTitle&gt;{title}&lt;/DialogTitle&gt;
          &lt;DialogDescription&gt;
            Edit the data for your chart. You can add, remove, and modify data
            points.
          &lt;/DialogDescription&gt;
        &lt;/DialogHeader&gt;

        <div>
          <div>
            <div>
              <h3>
                {chartType === "label-value"
                  ? "Label & Value Data"
                  : "X & Y Coordinate Data"}
              </h3>
              &lt;Button onClick={addRow} size="sm" variant="outline"&gt;
                &lt;Plus className="h-4 w-4 mr-2" /&gt;
                Add Row
              &lt;/Button&gt;
            </div>

            <div>
              <table>
                &lt;TableHeader&gt;
                  &lt;TableRow&gt;
                    {chartType === "label-value" ? (
                      &lt;&gt;
                        &lt;TableHead className="w-[200px]"&gt;Label&lt;/TableHead&gt;
                        &lt;TableHead className="w-[150px]"&gt;Value&lt;/TableHead&gt;
                        &lt;TableHead className="w-[50px]"&gt;Actions&lt;/TableHead&gt;
                      &lt;/&gt;
                    ) : (
                      &lt;&gt;
                        &lt;TableHead className="w-[150px]"&gt;X&lt;/TableHead&gt;
                        &lt;TableHead className="w-[150px]"&gt;Y&lt;/TableHead&gt;
                        &lt;TableHead className="w-[50px]"&gt;Actions&lt;/TableHead&gt;
                      &lt;/&gt;
                    )}
                  &lt;/TableRow&gt;
                &lt;/TableHeader&gt;
                &lt;TableBody&gt;
                  {(localData as (LabelValueData | XYData)[]).map(
                    (row, index) =&gt; (
                      &lt;TableRow key={index}&gt;
                        {chartType === "label-value" ? (
                          &lt;&gt;
                            &lt;TableCell&gt;
                              <div>
                                <input>
                                    updateRow(index, "label", e.target.value)
                                  }
                                  placeholder="Enter label"
                                  className={
                                    getRowValidationError(index, "label")
                                      ? "border-red-500"
                                      : ""
                                  }
                                /&gt;
                                {getRowValidationError(index, "label") && (
                                  <p>
                                    {getRowValidationError(index, "label")}
                                  </p>
                                )}
                              </div>
                            &lt;/TableCell&gt;
                            &lt;TableCell&gt;
                              <div>
                                <input type="number">
                                    updateRow(index, "value", e.target.value)
                                  }
                                  placeholder="0"
                                  className={
                                    getRowValidationError(index, "value")
                                      ? "border-red-500"
                                      : ""
                                  }
                                /&gt;
                                {getRowValidationError(index, "value") && (
                                  <p>
                                    {getRowValidationError(index, "value")}
                                  </p>
                                )}
                              </div>
                            &lt;/TableCell&gt;
                          &lt;/&gt;
                        ) : (
                          &lt;&gt;
                            &lt;TableCell&gt;
                              <div>
                                <input type="number">
                                    updateRow(index, "x", e.target.value)
                                  }
                                  placeholder="0"
                                  className={
                                    getRowValidationError(index, "x")
                                      ? "border-red-500"
                                      : ""
                                  }
                                /&gt;
                                {getRowValidationError(index, "x") && (
                                  <p>
                                    {getRowValidationError(index, "x")}
                                  </p>
                                )}
                              </div>
                            &lt;/TableCell&gt;
                            &lt;TableCell&gt;
                              <div>
                                <input type="number">
                                    updateRow(index, "y", e.target.value)
                                  }
                                  placeholder="0"
                                  className={
                                    getRowValidationError(index, "y")
                                      ? "border-red-500"
                                      : ""
                                  }
                                /&gt;
                                {getRowValidationError(index, "y") && (
                                  <p>
                                    {getRowValidationError(index, "y")}
                                  </p>
                                )}
                              </div>
                            &lt;/TableCell&gt;
                          &lt;/&gt;
                        )}
                        &lt;TableCell&gt;
                          &lt;Button
                            variant="ghost"
                            size="sm"
                            onClick={() =&gt; removeRow(index)}
                            disabled={
                              (localData as (LabelValueData | XYData)[])
                                .length &lt;= 1
                            }
                          &gt;
                            &lt;Trash2 className="h-4 w-4" /&gt;
                          &lt;/Button&gt;
                        &lt;/TableCell&gt;
                      &lt;/TableRow&gt;
                    ),
                  )}
                &lt;/TableBody&gt;
              </table>
            </div>

            {(localData as (LabelValueData | XYData)[]).length === 0 && (
              <div>
                No data points. Click "Add Row" to get started.
              </div>
            )}
          </div>
        </div>

        &lt;DialogFooter&gt;
          &lt;Button variant="outline" onClick={handleCancel}&gt;
            Cancel
          &lt;/Button&gt;
          &lt;Button onClick={handleSave} disabled={!validateData()}&gt;
            Save Changes
          &lt;/Button&gt;
        &lt;/DialogFooter&gt;
      &lt;/DialogContent&gt;
    &lt;/Dialog&gt;
  );
}
